package com.littlerpc.protocol.net.common;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 *
 * @author ChengPeng
 * @date 2017/6/16
 */
public final class ServiceBeanResource {

    private static Map<String, Object> serviceMap = new HashMap<>();

    public void startServer(){

    }

    /**
     * 执行方法
     */
    public static RpcResponse invokeService(RpcRequest request) {

        if (serviceMap.size() == 0) {
            return null;
        }


        String requestId = request.getRequestId();
        String className = request.getClassName();
        String methodName = request.getMethodName();
        Object[] parameters = request.getParameters();
        Class<?>[] parameterTypes = request.getParameterTypes();

        // 获取class对应的实现类
        Object impl = serviceMap.getOrDefault(className, null);
        RpcResponse response = new RpcResponse();
        response.setRequestId(requestId);

        try {
            //获取方法描述
            Method method = impl.getClass().getMethod(methodName, parameterTypes);
            //调用方法
            Object result = method.invoke(impl, parameters);
            response.setResult(result);

        } catch (Exception e) {
            response.setError(e);
            e.printStackTrace();
        }
        return response;
    }


    public static void putService(String key, Object serviceBean) {
        serviceMap.putIfAbsent(key,serviceBean);
    }

}
